//
//  Networking.swift
//  WanAndroidLearn
//
//  Created by TRS-Mobile on 2023/10/31.
//

import Foundation
import Moya
import MoyaSugar
import RxSwift

let networking = Networking<WanAndroidAPI>()

class Networking<Target: SugarTargetType>: MoyaSugarProvider<Target> {
    init(plugins: [PluginType] = []) {
        let session = MoyaProvider<Target>.defaultAlamofireSession()
        session.sessionConfiguration.timeoutIntervalForRequest = 20
        super.init(session: session, plugins: plugins)
    }
    
    func request(_ target: Target,
                 file: StaticString = #file,
                 function: StaticString = #function,
                 line: UInt = #line)
    -> Single<Response> {
        let requestString = "\(target.method.rawValue) \(target.path)"
        return self.rx.request(target)
            .filterSuccessfulStatusCodes()
            .do { value in
                let msg = "SUCCESS: \(requestString) (\(value.statusCode)"
                log.debug(msg, file: file, function: function, line: line)
            } onError: { error in
                let msg: String
                if let response = (error as? MoyaError)?.response {
                    if let jsonObject = try? response.mapJSON(failsOnEmptyData: false) {
                        msg = "FAILURE: \(requestString) (\(response.statusCode))\n\(jsonObject)"
                    } else if let rawString = try? response.mapString() {
                        msg = "FAILURE: \(requestString) (\(response.statusCode))\n\(rawString)"
                    } else {
                        msg = "FAILURE: \(requestString) (\(response.statusCode))"
                    }
                } else {
                    msg = "FAILURE: \(requestString)\n\(error)"
                }
                log.warning(msg, file: file, function: function, line: line)
            } onSubscribe: {
                let message = "REQUEST: \(requestString)"
                log.debug(message, file: file, function: function, line: line)
            }
    }
}
